// Package internal 应用中心
package internal

import (
	"sync"
	"time"

	"github.com/robfig/cron"

	"net/http"
	_ "net/http/pprof" // pprof debug

	"gitee.com/serialnumber/internal/models"
	"gitee.com/serialnumber/internal/supports"
	"github.com/micro/go-log"
)

// Application struct
type Application struct {
	handle map[int]*Generate
	supports.Wrapper
	mux sync.Mutex
}

func NewApplication() *Application {
	return &Application{
		handle: make(map[int]*Generate, 0),
	}
}

// Init func
func (app *Application) Init() error {
	return nil
}

type authCache struct {
	AuthType int
	Number   int
}

type productCache struct {
	ID      string
	CodeNum int
}

// Start func
func (app *Application) Start() error {
	go func() {
		http.ListenAndServe(":9999", nil)
	}()
	models.InitDB()
	log.Log("哈哈是几点了飞机来说")
RESTART_CRONTAB:
	c := cron.New()
	c.AddFunc("0 10 14 * * ?", app.runCronTab)
	go c.Start()

	tc := time.NewTicker(1 * time.Second)
	//tm, _ := time.ParseInLocation(supports.StandardDateFormat, "2020-07-05 11:20:00", time.Local)
	tm := time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 14, 11, 0, 0, time.Local).Unix()

	for range tc.C {
		if time.Now().Unix() == tm {
			authList := make([]*authCache, 0)
			for i := 0; i < 9; i++ {
				authList = append(authList, &authCache{AuthType: i})
			}

			// init 900 instance
			for _, auth := range authList {
				handle, ok := app.handle[auth.AuthType]
				if ok {
					delete(app.handle, auth.AuthType)
					handle.Stop()
				}
			}
			c.Stop()
			tc.Stop()
			log.Log("实例已退出完毕...............")
			goto RESTART_CRONTAB
		}
	}
	return nil
}

func (app *Application) runCronTab() {
	log.Log("计划任务开始啦")
	authList := make([]*authCache, 0)
	for i := 0; i < 9; i++ {
		authList = append(authList, &authCache{AuthType: i})
	}

	// init 900 instance
	for _, auth := range authList {
		generate := NewGenerate(auth.AuthType)
		app.handle[auth.AuthType] = generate
		app.Wrap(generate.Run)
	}
}

// Stop func
func (app *Application) Stop() error {
	return nil
}
